<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 提示注意 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
      >
      </el-alert>
      <!-- 商品分类 -->
      <el-row class="row_top">
        <el-col class="col_pore">
          <span>设置商品分类：</span>
          <!-- 级联选择器 -->
          <el-cascader
            v-model="cascaderparams"
            :options="paramsoptions"
            :props="paramsprops"
            @change="handleChange"
            expandTrigger="hover"
            class="wd_select"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页区域 -->
      <el-tabs v-model="activeName" @tab-click="tabClick" class="row_top">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="reserveparams"
            @click="adddialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格区域 -->
          <el-table :data="getmanyData" border style="width: 100%">
            <el-table-column label="#" type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="item.attr_id"
                  closable
                  @close="handleclose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 添加tag标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.addinputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editmany(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removemany(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="reserveparams"
            @click="adddialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格区域 -->
          <el-table :data="getonlyData" border style="width: 100%">
            <el-table-column label="#" type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="item.attr_id"
                  closable
                  @close="handleclose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 添加tag标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.addinputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editmany(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removemany(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 修改参数或者属性的对话框 -->
      <el-dialog
        :title="'修改' + reserveactiveName"
        :visible.sync="editdialogVisible"
        width="50%"
        @close="closeEdit"
      >
        <el-form
          :model="editForm"
          :rules="editrules"
          ref="EditruleFormRef"
          label-width="100px"
        >
          <el-form-item :label="reserveactiveName" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editsubmitparams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加参数的对话框 -->
      <el-dialog
        :title="'添加' + reserveactiveName"
        :visible.sync="adddialogVisible"
        width="50%"
        @close="closeAdd"
      >
        <el-form
          :model="addForm"
          :rules="addrules"
          ref="ruleFormRef"
          label-width="100px"
        >
          <el-form-item :label="reserveactiveName" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="adddialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addsubmitparams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 存储选择的id
      cascaderparams: [],
      // 商品分类列表
      paramsoptions: [],
      adddialogVisible: false,
      // 添加参数和属性的表单
      addForm: {
        attr_name: ''
      },
      // 添加参数和属性的表单验证规则
      addrules: {
        attr_name: [
          { required: true, message: '请输入添加的名称', trigger: 'blur' }
        ]
      },
      // 修改对话框
      editdialogVisible: false,
      editForm: {
        attr_name: ''
      },
      editrules: {
        attr_name: [
          { required: true, message: '请输入添加的名称', trigger: 'blur' }
        ]
      },
      // 用来存储属性id
      attrId: '',
      // 级联选择对象
      paramsprops: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 标签ye
      activeName: 'many',
      // 动态参数
      getmanyData: [],
      // 静态属性
      getonlyData: []
      // 这是控制tag添加框的数据
      // inputVisible: false,
      // // tag框输入的数据
      // addinputValue: ''
    }
  },
  created() {
    this.getlist()
  },
  methods: {
    // 级联选择监听函数
    handleChange() {
      // console.log(this.cascaderparams)
      if (this.cascaderparams.length !== 3) {
        this.cascaderparams = []
        this.getmanyData = []
        this.getonlyData = []
        return
      }
      // 发起请求获取参数和属性
      this.getattributes()
    },
    // 获取商品分类列表
    async getlist() {
      const { data: res } = await this.$http.get('categories')
      //   console.log(res)
      this.paramsoptions = res.data
    },
    tabClick() {
      //   console.log(this.activeName)
      this.getattributes()
    },
    // 获取商品属性
    async getattributes() {
      const { data: res } = await this.$http.get(
        `categories/${this.reserveId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      // console.log(res.data)
      // 这是制作每个参数或者属性下的tag标签
      res.data.forEach((item) => {
        // 这是利用split方法去将字符串转换成数组，当遇到空的时候转换成[11,222,33] 形式 。并且判断原先的字符串是否为空
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.addinputValue = ''
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.getmanyData = res.data
      } else {
        this.getonlyData = res.data
      }
    },
    // 对话框关闭清除
    closeAdd() {
      this.$refs.ruleFormRef.resetFields()
    },
    // 对话框的提交
    addsubmitparams() {
      // 进行表单与验证
      this.$refs.ruleFormRef.validate(async (validate) => {
        if (!validate) {
          return this.$message.error('请输入名称')
        }
        const { data: res } = await this.$http.post(
          `categories/${this.reserveId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        // console.log(res)
        if (res.meta.status !== 201) {
          return
        }
        this.$message.success('添加成功')
        this.getattributes()
        this.adddialogVisible = false
      })
    },
    closeEdit() {
      this.$refs.EditruleFormRef.resetFields()
    },
    // 点击编辑动态参数
    async editmany(info) {
      // console.log(info)
      this.attrId = info.attr_id
      // 根据id获取对应信息
      const { data: res } = await this.$http.get(
        `categories/${this.reserveId}/attributes/${this.attrId}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      )
      if (res.meta.status !== 200) {
        return
      }
      // console.log(res)
      this.editForm.attr_name = res.data.attr_name
      this.editdialogVisible = true
    },
    // 提交修改的属性
    editsubmitparams() {
      // 先进行表单预先验证
      this.$refs.EditruleFormRef.validate(async (validate) => {
        if (!validate) {
          return this.$message.error('请输入修改的名称')
        }
        // 发起请求
        const { data: res } = await this.$http.put(
          `categories/${this.reserveId}/attributes/${this.attrId}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        this.getattributes()
        this.editdialogVisible = false
        this.$message.success('修改成功')
      })
    },
    // 删除属性
    async removemany(info) {
      console.log(info)
      const Result = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (Result !== 'confirm') {
        return this.$message.info('已经取消了删除')
      }
      // 发起删除请求
      const { data: res } = await this.$http.delete(
        `categories/${this.reserveId}/attributes/${info.attr_id}`
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('删除失败')
      }
      this.getattributes()
      this.$message.success('删除成功')
    },
    // 点击添加tag事件
    showInput(info) {
      info.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 监听tag标签 失去焦点或者按钮enter 改变的事件
    async handleInputConfirm(row) {
      if (row.addinputValue.trim().length === 0) {
        row.inputVisible = false
        row.addinputValue = ''
        return
      }
      // 将输入的数据添加到row里面
      row.attr_vals.push(row.addinputValue.trim())
      row.inputVisible = false
      row.addinputValue = ''
      this.setattrbute(row)
    },
    async setattrbute(row) {
      // 发起请求将数据保存在服务端
      const { data: res } = await this.$http.put(
        `categories/${this.reserveId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(',')
        }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('创建失败')
      }
      // row.attr_vals = res.data.attr_vals.split(' ')
      this.$message.success('添加属性成功')
    },
    // 删除标签
    handleclose(i, row) {
      row.attr_vals.splice(i, 1)
      this.setattrbute(row)
    }
  },
  // 计算属性监听器
  computed: {
    reserveparams() {
      if (this.cascaderparams.length !== 3) {
        return true
      }
      return false
    },
    // 获取级联选择器中三级分类的id
    reserveId() {
      if (this.cascaderparams.length === 3) {
        return this.cascaderparams[2]
      }
      return null
    },
    // 判断是添加属性还是添加参数
    reserveactiveName() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.wd_select {
  width: 300px;
}
.row_top {
  margin-top: 20px;
}
.input-new-tag {
  width: 120px;
}
.el-tag {
  margin-left: 10px;
}
.input-new-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
}
// .col_pore {
//   position: relative !important;
// }
// .el-cascader__dropdown {
//   top: 223px !important;
// }
</style>